package com.castle.fortress.admin.contractType.service.impl;

import cn.hutool.core.util.StrUtil;

import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.contractType.entity.ContractTypeEntity;
import com.castle.fortress.admin.contractType.dto.ContractTypeDto;
import com.castle.fortress.admin.contractType.dto.ContractTypeTreeDto;
import com.castle.fortress.admin.contractType.mapper.ContractTypeMapper;
import com.castle.fortress.admin.contractType.service.ContractTypeService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * 合同类型表 服务实现类
 *
 * @author
 * @since 2025-04-22
 */
@Service
public class ContractTypeServiceImpl extends ServiceImpl<ContractTypeMapper, ContractTypeEntity> implements ContractTypeService {
    /**
    * 获取查询条件
    * @param contractTypeDto
    * @return
    */
    public QueryWrapper<ContractTypeEntity> getWrapper(ContractTypeDto contractTypeDto){
        QueryWrapper<ContractTypeEntity> wrapper= new QueryWrapper();
        if(contractTypeDto != null){
            ContractTypeEntity contractTypeEntity = ConvertUtil.transformObj(contractTypeDto,ContractTypeEntity.class);
            wrapper.like(contractTypeEntity.getId() != null,"id",contractTypeEntity.getId());
            wrapper.like(StrUtil.isNotEmpty(contractTypeEntity.getTypeName()),"type_name",contractTypeEntity.getTypeName());
            wrapper.like(StrUtil.isNotEmpty(contractTypeEntity.getTypeValue()),"type_value",contractTypeEntity.getTypeValue());
			wrapper.eq(contractTypeEntity.getLevel() != null,"level",contractTypeEntity.getLevel());
            wrapper.like(contractTypeEntity.getParentId() != null,"parent_id",contractTypeEntity.getParentId());
            wrapper.like(contractTypeEntity.getSortOrder() != null,"sort_no",contractTypeEntity.getSortOrder());
            wrapper.like(contractTypeEntity.getCreateTime() != null,"create_time",contractTypeEntity.getCreateTime());
            wrapper.like(contractTypeEntity.getUpdateTime() != null,"update_time",contractTypeEntity.getUpdateTime());
            wrapper.like(contractTypeEntity.getCreateUser() != null,"create_user",contractTypeEntity.getCreateUser());
            wrapper.like(contractTypeEntity.getUpdateUser() != null,"update_user",contractTypeEntity.getUpdateUser());
			wrapper.eq(contractTypeEntity.getIsDeleted() != null,"is_deleted",contractTypeEntity.getIsDeleted());
        }
        return wrapper;
    }

    @Override
    public IPage<ContractTypeTreeDto> pageContractType(Page<ContractTypeTreeDto> page, ContractTypeDto contractTypeDto) {
        // 获取所有合同类型数据
        List<ContractTypeEntity> list = baseMapper.selectList(getWrapper(contractTypeDto));
        List<ContractTypeDto> dtoList = ConvertUtil.transformObjList(list, ContractTypeDto.class);
        
        // 转换为树形结构
        List<ContractTypeTreeDto> treeDtos = ConvertUtil.transformObjList(dtoList, ContractTypeTreeDto.class);
        
        // 构建树形结构
        List<ContractTypeTreeDto> rootNodes = new ArrayList<>();
        Map<Long, ContractTypeTreeDto> nodeMap = treeDtos.stream()
            .collect(Collectors.toMap(ContractTypeTreeDto::getId, node -> node));
            
        for (ContractTypeTreeDto node : treeDtos) {
            if (node.getParentId() == null || node.getParentId() == 0L) {
                rootNodes.add(node);
            } else {
                ContractTypeTreeDto parent = nodeMap.get(node.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }
        
        // 对每个节点的子节点按sortOrder排序
        sortTreeNodes(rootNodes);
        
        // 计算分页
        int total = rootNodes.size();
        int start = (int) ((page.getCurrent() - 1) * page.getSize());
        int end = Math.min(start + (int) page.getSize(), total);
        
        // 创建分页结果
        Page<ContractTypeTreeDto> resultPage = new Page<>(page.getCurrent(), page.getSize(), total);
        if (start < total) {
            resultPage.setRecords(rootNodes.subList(start, end));
        } else {
            resultPage.setRecords(new ArrayList<>());
        }
        
        return resultPage;
    }

    @Override
    public List<ContractTypeTreeDto> listContractType(ContractTypeDto contractTypeDto) {
        QueryWrapper<ContractTypeEntity> wrapper = getWrapper(contractTypeDto);
        List<ContractTypeEntity> list = baseMapper.selectList(wrapper);
        List<ContractTypeDto> dtoList = ConvertUtil.transformObjList(list, ContractTypeDto.class);
        
        // 转换为树形结构
        List<ContractTypeTreeDto> treeDtos = ConvertUtil.transformObjList(dtoList, ContractTypeTreeDto.class);
        
        // 构建树形结构
        List<ContractTypeTreeDto> rootNodes = new ArrayList<>();
        Map<Long, ContractTypeTreeDto> nodeMap = treeDtos.stream()
            .collect(Collectors.toMap(ContractTypeTreeDto::getId, node -> node));
            
        for (ContractTypeTreeDto node : treeDtos) {
            if (node.getParentId() == null || node.getParentId() == 0L) {
                rootNodes.add(node);
            } else {
                ContractTypeTreeDto parent = nodeMap.get(node.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }
        
        // 对每个节点的子节点按sortOrder排序
        sortTreeNodes(rootNodes);
        
        return rootNodes;
    }
    
    /**
     * 递归排序树节点
     * @param nodes 节点列表
     */
    private void sortTreeNodes(List<ContractTypeTreeDto> nodes) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }
        
        // 按sortOrder排序当前层级节点
        nodes.sort((a, b) -> {
            if (a.getSortOrder() == null) return 1;
            if (b.getSortOrder() == null) return -1;
            return a.getSortOrder().compareTo(b.getSortOrder());
        });
        
        // 递归排序子节点
        for (ContractTypeTreeDto node : nodes) {
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                sortTreeNodes(node.getChildren());
            }
        }
    }
}

